<?php

class Model_Manager extends Model
{
    public function getItemsLimit($section, $limit=6, $order = 'name', $orderDir = 'ASC') {
        $items = $this->db->query('SELECT * FROM `directoryItems` WHERE `section`=? AND `isCategory` = 0 ORDER BY `' . $order . '` ' . $orderDir . ' LIMIT ' . $limit, $section)->fetchAll();
        $result = array();
        foreach ($items as $item) {
            $result[$item['id']] = $item;
        }
        return $result;
    }
    public function getItemsLimitParrentAlias($section, $limit=6, $order = 'name', $orderDir = 'ASC') {
        $items = $this->db->query('SELECT * FROM `directoryItems` WHERE `section`=? AND `isCategory` = 0 ORDER BY `' . $order . '` ' . $orderDir . ' LIMIT ' . $limit, $section)->fetchAll();
        $result = array();
        foreach ($items as $item) {
            $result[$item['id']] = $item;
        }
        return $result;
    }
    public function getChidrenCategoriesByAlias($alias, $section, $order = 'name', $orderDir = 'ASC') {
        $categories = $this->db->query('SELECT * FROM `directoryItems` WHERE `section`=? AND `alias`=? AND `isCategory` = 1 ORDER BY `' . $order . '` ' . $orderDir, array($section, $alias))->fetch();
        return $this->db->query('SELECT * FROM `directoryItems` WHERE `parentId`=? AND `section`=? AND `isCategory` = 1 ORDER BY `' . $order . '` ' . $orderDir, array($categories['id'], $section))->fetchAll();
    }
    public function getCategoryItemsByAlias($alias, $section, $page, $limit=8) {
        $startFrom=$page*$limit;
        $categoryData = $this->db->query('SELECT * FROM `directoryItems` WHERE `alias`=? AND `section`=? AND `isCategory` = 1 LIMIT 1', array($alias, $section))->fetch();
        $items = $this->db->query('SELECT * FROM `directoryItems` WHERE `parentId`=? AND `section`=? AND `isCategory` = 0 LIMIT ' . $startFrom . ',' . $limit, array($categoryData['id'], $section))->fetchAll();
//        system::dump($categoryData);exit();
        $result = array();
        foreach ($items as $item) {
            $result[] = $item;
        }
        return $result;
    }
    public function paginatorNavigator($categoryId, $section, $limit=6, $page=0, $link=NULL) {
        $startFrom=$page*$limit;
        $countItems = $this->db->query('SELECT count(*) as allItemsCount FROM `directoryItems` WHERE `parentId`=? AND `section`=? AND `isCategory` = 0', array($categoryId, $section))->fetch();
        $allPages = ceil($countItems['allItemsCount'] / $limit);
        if ($link == NULL) {
            return $allPages;
            exit();
        }  //system::dump($page);exit();
        $paginatorData = '<div class="shop-paginator">';
        for ($i = 1; $i <= $allPages; $i++) {
            if ($i - 1 == $page) {
                $paginatorData .= $i . " \n";
            } else {
                $paginatorData .= '<a href="'.$link.'/'.$i.'" class="shop-paginator-page">'.$i."</a> \n";
            }
        }if($allPages<=1)$paginatorData='';
        $paginatorData .= '</div>';
        return $paginatorData;
    }
    public function getColors($section) {
        $images = $this->db->query('SELECT * FROM `directoryImages` WHERE `section`=? ORDER BY `name` ASC', $section)->fetchAll();
        $result = array();
        foreach ($images as $image) {
            $result[$image['name']] = $image;
        }
        return $result;
    }
    public function getSizes($section) {
        $images = $this->db->query('SELECT * FROM `directoryImages` WHERE `section`=? ORDER BY `name` ASC', $section)->fetchAll();
        $result = array();
        foreach ($images as $image) {
            $result[$image['name']] = $image;
        }
        return $result;
    }
    public function getImagesParrentKey($section) {
        $images = $this->db->query('SELECT * FROM `directoryImages` WHERE `section`=? ORDER BY `itemId` ASC', $section)->fetchAll();
        $result = array();
        $image=array();
        foreach ($images as $image) {
            $result[$image['itemId']][] = $image;
        }
        return $result;
    }

    
    public function getImageForCartUrl($itemId)
    {
        $image = $this->db->query('SELECT * FROM `directoryImages` WHERE `itemId`=? ORDER BY `itemId` ASC', $itemId)->fetch();
        
        if(!empty($image))
            {
                return '/content/directory/images/shop/shopItemInCart/'.substr($image['alias'],0,1).'/'.$image['alias'].'.jpg';
            }
          else
          {
              return '/images/cart_noimg.png';
          }
    }
    
    

    public function selectUser($userId) {
        return $this->db->query('SELECT * FROM `users` WHERE `id`=? LIMIT 1', $userId)->fetch();
       // system::dump($this->db->query('SELECT * FROM `users` WHERE `id`=? LIMIT 1', $userId)->fetch());exit();
    }

    public function selectMember($userId,$name1=null,$name2=null) {
        $data=$this->db->query('SELECT * FROM `members` WHERE `user_id`=? LIMIT 1', $userId)->fetch();
        if($data==null){
            $this->db->query('INSERT INTO `members` (`user_id`,`name1`,`name2`)VALUES("'.$userId.'","'.$name1.'","'.$name2.'")')->insertId();
            $data=$this->db->query('SELECT * FROM `members` WHERE `user_id`=? LIMIT 1', $userId)->fetch();
        }
        return $data;
    }
    public function setMember($userId,$name1=null,$name2=null,$gender=null) {
        return $this->db->query('UPDATE `members` SET `name1`=?,`name2`=?,`gender`=? WHERE `user_id`=?', array($name1,$name2,$gender,$userId))->insertId();
    }

    //functions for texts
    public function getText($category)
    {
       $parentId = $this->db->query("SELECT `id` FROM `directoryItems` WHERE `name`=? AND `isCategory`=1 ",$category)->fetch();
       return $this->db->query('SELECT * FROM `directoryItems` WHERE `parentId` = ?',$parentId['id'])->fetchAll();
    }

    public function getShipping($userId) {
        return $this->db->query('SELECT * FROM `shippingAdress` WHERE `user_id`=?', $userId)->fetchAll();
    }
//    public function shipping($userId) {
//        $data=$this->db->query('SELECT * FROM `shippingAdress` WHERE `user_id`=?', $userId)->fetchAll();
//        if(empty($data)){
//            $this->db->query('INSERT INTO `shippingAdress` (`user_id`)VALUES("'.$userId.'")')->insertId();
//            $data=$this->db->query('SELECT * FROM `shippingAdress` WHERE `user_id`=?', $userId)->fetchAll();
//        }
//        return $data;
//    }
    public function addShipping($userId,$name1,$name2,$country,$street,$city,$state,$postal,$phone,$primary) {
        return$this->db->query('INSERT INTO `shippingAdress` (`user_id`,`name1`,`name2`,`country`,`street`,`city`,`state`,`postal`,`phone`,`primary`)VALUES("'.$userId.'","'.$name1.'","'.$name2.'","'.$country.'","'.$street.'","'.$city.'","'.$state.'","'.$postal.'","'.$phone.'","'.$primary.'")')->insertId();
    }
    public function updateShipping($id,$userId,$name1,$name2,$country,$street,$city,$state,$postal,$phone,$primary) {
        return$this->db->query('UPDATE `shippingAdress` SET `name1`=?,`name2`=?,`country`=?,`street`=?,`city`=?,`state`=?,`postal`=?,`phone`=?
        WHERE `id`=? AND `user_id`=?', array($name1,$name2,$country,$street,$city,$state,$postal,$phone,$id,$userId))->insertId();
    }
    public function getShippingId($id,$userId) {
        return $this->db->query('SELECT * FROM `shippingAdress` WHERE `id`=? AND `user_id`=?  LIMIT 1', array($id,$userId))->fetch();
    }
    public function setPrimaryShipping($id,$userId) {
        $this->db->query('UPDATE `shippingAdress` SET `primary`=?
        WHERE `user_id`=?', array('0',$userId))->insertId();
        return$this->db->query('UPDATE `shippingAdress` SET `primary`=?
        WHERE `id`=? AND `user_id`=?', array('1',$id,$userId))->insertId();
    }
    public function dropShipping($id,$userId) {
        return $this->db->query('DELETE FROM `shippingAdress`WHERE `id`=? AND `user_id`=? LIMIT 1', array($id,$userId))->insertId();
    }
    public function getPrimary($userId) {
        return $this->db->query('SELECT * FROM `shippingAdress` WHERE `user_id`=? AND `primary`=1', $userId)->fetchAll();
    }

    
    public function getMainPageImage($position)
    {
        $itemId = $this->db->query("SELECT * FROM `directoryItems` WHERE `section`= 'main' LIMIT 1")->fetch();
        
        $image = $this->db->query('SELECT * FROM `directoryImages` WHERE `itemId`=? AND `select1` = ? ORDER BY `itemId` ASC', array($itemId['id'],$position) )->fetch();
        
        switch ($image['select2']) 
        {
            case 0:
                $image['url'] = '/shop/category/women/';
                break;
            case 1:
                $image['url'] = '/shop/category/men/';
                break;
            case 2:
                $image['url'] = '/shop/category/kids/';
                break;
            case 3:
                $image['url'] = '/shop/category/accessories/';
                break;
        }
        
        switch ($image['select1']) 
        {
            case 0:
                $size = 'first_index';
                break;
            case 1:
                $size = 'second_index';
                break;
            case 2:
                $size = 'third_index';
                break;
            case 3:
                $size = 'fourth_index';
                break;
        }
        
        $image['src'] = $this->imagePath($image['section'], $size, $image['alias']);
        
        return $image;
    }
    
    public function imagePath($section, $size,$alias, $extension = 'jpg')
    {
            return '/content/directory/images/' . $section . '/' . $size . '/' . substr($alias, 0, 1) . '/' . $alias . '.' . $extension;
    }
    
    public function getSuggestions($id,$parentId)
    {
        $suggestions =  $this->db->query("SELECT * FROM `directoryItems` WHERE `parentId`=? AND `id` <>?  ORDER BY RAND() LIMIT 3",array($parentId,$id))->fetchAll();
        $suggests=array();
        foreach ($suggestions as $suggest) {
//            $suggest['img'] = $this->imagePath($suggest['section'], 'shopItemRecent', $suggest['alias']);
           $suggests[] .= array('image'=>'img');
        }
        system::dump($suggests);exit();
//       return $suggestions;
    }
    
}

